<?php

/**
 * 邮件队列
 * The followings are the available columns in table '{{refund}}':
 */
class MailQueue
{
	//邮件队列存放路径
	public $mailQueuePath = 'application.runtime.mailqueue';
	//执行队列休眠时间
	public $interval=3;// 每隔3s运行一个循环
	//单次循环发送邮件数量
	public $queueNumber=100;// 每循环发送邮件100
	//邮件表名称 
	public $mailClass = "Emails";
	//邮件表字段：成功数量
	public $successCodeName = "zml_success";
	//邮件表字段：失败数量
	public $errorCodeName = "zml_error";
	//邮件表字段：失败邮件地址记录
	public $errorMailCodeName = "zml_errormail";
	//邮件发送完成修改的状态
	public $changeStatus = array('zml_status'=>2);
	
	/**
	 * 创建邮件队列
	 * @param str    $title 邮件标题
	 * @param array  收件人列表
	 * @param text   $content 邮件内容
	 * @param int    $logid 邮件表记录ID
	 */
	public function CreateQueue($title,$tomail,$content,$logid){
		$data['title'] = $title;
		$data['tomail'] = $tomail;
		$data['Content'] = $content;
		$data['logid'] = $logid;
		$file = self::getFile().DIRECTORY_SEPARATOR."mailqueue_{$logid}.php";
		Tool::saveDataToFile($data,$file);
	}

	/**
	 * 执行邮件发送队列，
	 */
	public function run(){
		$queueFile = scandir($this->getFile());
		natcasesort($queueFile);
		foreach($queueFile as $val){
			$ext = strrchr($val, '.');
			if($ext == '.php'){
				$file = $this->getFile().DIRECTORY_SEPARATOR.$val;
				$data = include($file);
				$success = 0;
				$error = 0;
				$errorMail = array();
				//将收件人分割成小组
				$tomailarr = array_chunk($data['tomail'],$this->queueNumber, true);
				foreach($tomailarr as $val){
					foreach($val as $key=>$val2){
						//发送邮件
						if(self::sentQueueMail($val2,$data['title'].$key,htmlspecialchars_decode($data['Content']))){
							//成功
							$success++;
						}else{
							//失败
							$error++;
							$errorMail[] = $val2;
						}
					}
					sleep($this->interval);// 休眠时间
				}
				//执行完操作,修改数据库
				$emails = Emails::model()->findByPk($data['logid']);
				$emails->zml_success = $success;
				$emails->zml_error = $error;
				$emails->zml_errormail = join(',',$errorMail);
				$emails->zml_status = 2;
				$emails->save();
				//删除队列文件
				unlink($file);
			}
		}
	}
	
	/**
	 * 发送邮件
	 * 
	 */
	public function sentQueueMail($tomail,$title,$content){
		$mail = Yii::app()->mailer;
		$mail->AddReplyTo($tomail);
		$mail->AddAddress($tomail);
		$mail->Subject = $title;
		$params['message'] = $content;
		$mail->getView('message', array('params'=>$params,'mailer'=>$mail),'member');
		return $mail->Send();
	}
	
	/**
	 * 获取列队文件目录
	 */
	public function getFile(){
		$path = Yii::getPathOfAlias($this->mailQueuePath);
		if(!is_dir($path)){
			if(!Tool::makedir($path)){
				$this->throwException('创建目录失败,请检查磁盘空间或者权限!');
			}
		}
		return $path;
	}

}